var editor;

if (editorType == "1") {
    editor = UE.getEditor('content');
} else {
    var width = $(window).width() - 230 - 150;
    $.get(ulewo.absolutePath + '/resource/markdown/readme.md', function (md) {
        editor = editormd("content", {
            width: width,
            height: "500",
            path: ulewo.absolutePath + '/resource/markdown/lib/',
            theme: "defualt",
            previewTheme: "defualt",
            editorTheme: "defualt",
            markdown: md,
            codeFold: true,
            toolbarIcons: function () {
                // Or return editormd.toolbarModes[name]; // full, simple, mini
                // Using "||" set icons align right.
                return ["undo", "redo", "bold", "del", "italic", "quote", "uppercase", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "link", "reference-link", "image", "code-block", "table", "datetime", "html-entities", "watch", "preview", "fullscreen", "clear", "help"]
            },
            //syncScrolling : false,
            saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
            searchReplace: true,
            //watch : false,                // 关闭实时预览
            htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启
            //toolbar  : false,             //关闭工具栏
            //previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
            emoji: true,
            taskList: true,
            tocm: true,         // Using [TOCM]
            tex: true,                   // 开启科学公式TeX语言支持，默认关闭
            flowChart: true,             // 开启流程图支持，默认关闭
            sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
            //dialogLockScreen : false,   // 设置弹出层对话框不锁屏，全局通用，默认为true
            //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
            //dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为true
            //dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为0.1
            //dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp"],
            imageUploadURL: ulewo.absolutePath + '/ueditorImageUpload.action',
            onload: function () {
                // console.log('onload', this);
                //this.fullscreen();
                //this.unwatch();
                //this.watch().fullscreen();

                //this.setMarkdown("#PHP");
                //this.width("100%");
                //this.height(480);
                //this.resize("100%", 640);
            }
        });
    });
}


ulewo.url = {
    saveBlog: "save_blog.action", saveDraftsBlog: "save_drafts_blog.action"
}
ulewo.autoSveTime = 180000;// 1000*60*3=180000 3分钟保存一次草稿
ulewo.topicType = {
    topicType0: 0,// 普通帖
    topicType1: 1
// 投票帖
}

var uploader = WebUploader.create({
    // 选完文件后，是否自动上传。
    auto: true,

    // swf文件路径
    swf: ulewo.absolutePath + '/resource/webuploader/Uploader.swf',

    // 文件接收服务端。
    server: ulewo.absolutePath + '/fileUpload.action',

    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: {
        id: '#filePicker', multiple: false
    },
    // 只允许选择excel。
    duplicate: 1, // 不去重
    compress: false, // 压缩
    fileSingleSizeLimit: 2 * 1024 * 1024
});
uploader.on('fileQueued', function (file) {
    var name = file.name;
    var type = name.substring(name.lastIndexOf(".") + 1);
    if (type != "rar" && type != "zip") {
        uploader.removeFile(file);
        alert("文件只能是.rar或者.zip");
        return;
    }
    $("#filePicker").hide();
    $("#loading-upload").show();
});

uploader.on('uploadSuccess', function (file, response) {
    if (response.responseCode == "200") {
        $("<div>" + file.name + "&nbsp;&nbsp;<a href='javascript:deleteFile()'>删除</a></div>").appendTo($("#file-list"));
        $("#attached_file_name").val(file.name);
        $("#attached_file").val(response.savePath);
    }
    $("#file_upload").hide();
    $("#uploading").hide();
});

uploader.on('error', function (handler) {
    if (handler == "F_EXCEED_SIZE") {
        alert("文件不能超过2M");
    }
});

function deleteFile() {
    $.ajax({
        async: true, cache: false, type: 'POST', dataType: "json", data: {
            fileName: $("#attached_file").val()
        }, url: ulewo.absolutePath + "/deleteFile.action",// 请求的action路径
        success: function (data) {
            if (data.result = "200") {
                $("#filePicker").show();
                $("#loading-upload").hide();
                $("#file_upload").show();
                $("#attached_file_name").val("");
                $("#attached_file").val("");
                $("#file-list").empty();
            } else {
                alert("删除失败");
            }
        }
    });
};


$(function () {
    $("#post-btn").click(function () {
        postBlog();
    });

    var attached_file = $("#attached_file").val();
    var attached_file_name = $("#attached_file_name").val();
    if (attached_file != "" && attached_file_name != "") {
        $("<div>" + attached_file_name + "&nbsp;&nbsp;<a href='javascript:deleteFile()'>删除</a></div>").appendTo($("#file-list"));
        $("#file_upload").hide();
        $("#uploading").hide();
    }
    var blogId = $("#blog-id").val();
    setInterval(function () {
        if (editorType == "1") {
            $("#richContent").val(editor.getContent());
        } else {
            $("#richContent").val(editor.getHTML());
        }
        ulewo.ajaxRequest({
            url: ulewo.url.saveDraftsBlog, showLoad: false, data: $("#post-form").serialize(), fun: function (res) {
                $("#blog-id").val(res.data);
                $("#auto-save-info").show();
                setTimeout(function () {
                    $("#auto-save-info").fadeOut("slow");
                }, 2000);

            }
        });
    }, ulewo.autoSveTime)
})

/**
 * 发表主题
 */
function postBlog() {
    var form = $("#post-form");
    var result = ulewo.checkForm(form);
    if (editorType == "1") {
        if (!editor.hasContents()) {
            ulewo.setError($("#content"), "内容不能为空");
            result = false;
        }
    } else {
        if ($.trim(editor.getHTML()) == "") {
            ulewo.setError($("#content"), "内容不能为空");
            result = false;
        }
    }

    if (!result) {
        return;
    }
    if (editorType == "1") {
        $("#richContent").val(editor.getContent());
    } else {
        $("#richContent").val(editor.getHTML());
    }
    var categoryId = $("select[name='categoryId']").val();
    if (categoryId == 0) {
        ulewo.confirm({
            msg: "分类没有选择，确认要提交吗？",
            fun: function () {
                ulewo.ajaxRequest({
                    url: ulewo.url.saveBlog, data: $("#post-form").serialize(), fun: function (res) {
                        ulewo.tipMsg({
                            type: "success", content: "发布成功，正在跳转到详情页......"
                        });
                        document.location.href = ulewo.absolutePath + "/user/" + ulewo.user.userId + "/blog/" + res.data;
                    }
                });
            }
        });
    } else {
        ulewo.ajaxRequest({
            url: ulewo.url.saveBlog, data: $("#post-form").serialize(), fun: function (res) {
                ulewo.tipMsg({
                    type: "success", content: "发布成功，正在跳转到详情页......"
                });
                document.location.href = ulewo.absolutePath + "/user/" + ulewo.user.userId + "/blog/" + res.data;
            }
        });
    }
}
